const Koa = require('koa');

const app = new Koa();

const static = require('koa-static');

const query = require('./db/index');

const path = require('path');

const router = require('koa-router')();

// const bodyparser = require('koa-bodyparser');

const bodyparser = require('./middleware/bodyparser');

const info = require('./middleware/info');

app.use(info())

//处理静态资源
app.use(static(path.join(__dirname,'./public/')));

app.use(bodyparser());

app.use(router.routes());

app.use(router.allowedMethods());

//添加成绩

router.post('/api/add',async (ctx,next) => {
    //向数据库内添加一条数据
    let {username,skill,theory} = ctx.params;
    console.log(username,skill,theory);
    //容错处理
    if(username && skill && theory){

        //是否已经存在
        let target = await query('select * from scorelist where username=?',[username]);
        if(target.length){
            //已经存在了
            ctx.body = {
                code:4,
                msg:'此用户名已存在'
            }
        }else{
            //不存在
            try{
                await query('insert into scorelist (username,skill,theory) values (?,?,?)',[username,skill,theory]);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})


//查询
router.get('/api/list',async (ctx) => {
    //分页 pagenum limit
    let {pagenum=1,limit=2} = ctx.params;
    let startIndex = (pagenum-1)*limit;
    let total = await query('select count(*) from scorelist');
    let list = await query(`select * from scorelist limit ${startIndex},${limit}`);

    ctx.body = {
        code:1,
        data:list,
        total:total[0]['count(*)']
    }
})

//修改
router.put('/api/update',async (ctx) => {
    let {username,skill,theory,id} = ctx.params;
    if(username&&skill&&theory&&id){
        try{
            await query('update scorelist set username=?,skill=?,theory=? where id=?',[username,skill,theory,id]);
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:e,
                msg:'修改失败'
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})


//删除
router.delete('/api/del',async (ctx) => {
    let {id} = ctx.params;
    if(id){
        try{
            await query('delete from scorelist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:e,
                msg:'修改失败'
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})


app.listen(3000,() => {
    console.log('服务启动成功')
})